package com.wl.org.controller;

import com.wl.basic.util.AjaxResult;
import com.wl.basic.util.PageList;
import com.wl.org.domain.Employee;
import com.wl.org.query.EmployeeQuery;
import com.wl.org.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 此类是emp的接口层
 */
@RestController
@RequestMapping("/emp")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    //查询所有emp
    @GetMapping
    public List<Employee> findAll(){
        return employeeService.loadAll();
    }
    //查询单个
    @GetMapping("/{id}")
    public Employee findById(@PathVariable("id")Long id){
        return employeeService.loadById(id);
    }
    //新增and修改
    @PutMapping
    public AjaxResult saveAndUpt(@RequestBody Employee employee){
        try {
            //判断是否有id
            if(employee.getId() == null){

                //等于null就执行新增
                employeeService.save(employee);

                //返回无参结果
                return new AjaxResult();
            }else {
                //有id就执行修改
                employeeService.update(employee);
                return new AjaxResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //失败就改值
            return new AjaxResult(false,"操作失败");
        }
    }
    //删除
    @DeleteMapping("/{id}")
    public AjaxResult deleteEmpById(@PathVariable("id")Long id){
        try {
            employeeService.remove(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    //分页
    @PostMapping
    public PageList<Employee> queryPage(@RequestBody EmployeeQuery employeeQuery){
        return employeeService.queryPage(employeeQuery);
    }

    //批量删除
    @PatchMapping
    public AjaxResult removeA(@RequestBody List<Long>ids){
        try {
            //执行删除
            employeeService.removeA(ids);

            //成功返回结果  默认是成功就使用无参构造就行
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            //失败就返回结果集 调用全参构造自己赋值
            return new AjaxResult(false,"删除失败");
        }
    }
}
